<template>
  <div class="StartSetting_1">
    <!-- 第一个盒子 -->
    <div class="box1">
      <div class="StartTitle">标题</div>
      <el-form class="el-form" :model="form">
        <div class="form-box">
          <el-form-item label="比赛标题：">
            <el-input
              v-model="form.active_name"
              maxlength="25"
              show-word-limit
              placeholder="请输入比赛标题"
            />
          </el-form-item>
        </div>
        <div class="form-box">
          <el-form-item label="副标题：">
            <el-input
              v-model="form.subhead"
              maxlength="20"
              show-word-limit
              placeholder="请输入副标题"
            />
          </el-form-item>
        </div>
        <div class="form-box">
          <el-form-item label="举办方：">
            <el-input
              v-model="form.sponsor_first"
              maxlength="20"
              show-word-limit
              placeholder="请输入举办方"
            />
          </el-form-item>
        </div>
        <div class="form-box">
          <el-form-item label="承办方：">
            <el-input
              v-model="form.sponsor_second"
              maxlength="20"
              show-word-limit
              placeholder="请输入承办方"
            />
          </el-form-item>
        </div>
      </el-form>
      <!-- 修改组别位置,新增组数 -->
      <div class="group-box">
        <div>
          <p>参赛组别:</p>
          <select id="customSelect" v-model="form.group">
            <option v-for="item in groupOptions" :key="item.value" :value="item.label">
              {{ item.label }}
            </option>
          </select>
        </div>
        <div id="group-num-box">
          <p>参赛组数:</p>
          <el-input
            id="group-num-input"
            v-model="form.group_num"
            style="width: 45px; margin: 0 10px"
          />
          <p>组</p>
        </div>
      </div>
    </div>
    <!-- 第二个盒子 -->
    <div class="box2">
      <div class="StartTitle">基本信息</div>
      <div class="custom-select-box">
        <!-- 倒计时样式 -->
        <div>
          倒计时样式:
          <select id="customSelect" v-model="form.selectedValue">
            <option v-for="item in styleOptions" :key="item.value" :value="item.label">
              {{ item.label }}
            </option>
          </select>
        </div>
      </div>

      <div class="select-box">
        <div class="radio-box">
          <div>倒计时时间:</div>
          <el-input v-model="form.time" style="max-width: 80px" placeholder="请输入" />
          <div>分</div>
        </div>

        <div class="radio-box">
          <div>倒计时提醒时间:</div>
          <select id="customSelect" v-model="form.remainTime">
            <option v-for="item in remainOptions" :key="item.value" :value="item.label">
              {{ item.label }}
            </option>
          </select>
          <div>秒</div>
        </div>

        <div class="radio-box">
          <div>超出时间样式:</div>
          <el-radio-group v-model="form.styleRadio">
            <el-radio :value="1">负数时长</el-radio>
            <el-radio :value="2">显示超时时长</el-radio>
          </el-radio-group>
        </div>

        <div class="radio-box">
          <div>结束时闪烁:</div>
          <el-radio-group v-model="form.glitterRadio">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="2">关闭</el-radio>
          </el-radio-group>
        </div>
      </div>

      <div class="chose-img">
        <div class="chose-box1">请选择背景:</div>
        <div class="img-box">
          <img
            v-for="(image, index) in images"
            :key="index"
            :src="image"
            :class="{ selected: form.selectedImage === image }"
            alt=""
            @click="selectImage(image)"
          />

          <div class="upload_img" @click="triggerFileInput">
            <el-icon @click="triggerFileInput"><Plus /></el-icon>
            <input
              ref="fileInput"
              type="file"
              style="display: none"
              accept="image/*"
              @change="onFileChange"
            />
          </div>
        </div>
      </div>

      <div class="file-box">
        <div class="chose-box2">上传选手名单:</div>
        <input ref="file" type="file" accept=".xlsx, .xls" @change="handleFileChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import './StartSetting_1.css'
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { store } from '../../store'
import * as XLSX from 'xlsx'

const form = reactive({
  active_name: store.formData.active_name,
  subhead: store.formData.subhead,
  sponsor_first: store.formData.sponsor_first,
  sponsor_second: store.formData.sponsor_second,
  selectedValue: store.formData.selectedValue,
  group: store.formData.group,
  group_num: Number(store.formData.group_num),
  time: store.formData.time,
  remainTime: store.formData.remainTime,
  styleRadio: store.formData.styleRadio,
  glitterRadio: store.formData.glitterRadio,
  selectedImage: store.formData.selectedImage,
  xuanshou: store.formData.xuanshou
})
import image1 from '../../images/党建.png'
import image2 from '../../images/红色公益.jpg'

const images = reactive([image1, image2])

// 选手导入的名单
const tableData = ref([])
// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (!file) {
    ElMessage({
      type: 'warning',
      message: '请选择一个Excel文件!'
    })
    return
  }

  const validExtensions = ['xlsx', 'xls', 'csv']
  const fileExtension = file.name.split('.').pop().toLowerCase()
  if (!validExtensions.includes(fileExtension)) {
    ElMessage({
      type: 'warning',
      message: '请选择一个有效的Excel文件!'
    })
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const importedData = XLSX.utils.sheet_to_json(worksheet)

      // 清空当前数据
      tableData.value = []

      // 假设Excel文件格式与初始数据格式一致
      importedData.forEach((item) => {
        tableData.value.push({
          id: item['比赛编号']
        })
      })

      ElMessage({
        type: 'success',
        message: '导入成功！'
      })
      console.log(tableData.value)
    } catch (error) {
      console.error('解析Excel文件失败:', error)
      ElMessage({
        type: 'error',
        message: '解析Excel文件失败!'
      })
    }
  }
  reader.readAsArrayBuffer(file)
  // form.xuanshou = tableData.value
}

const saveFormData = () => {
  // 将表单数据保存到全局状态
  store.formData = {
    active_name: form.active_name,
    subhead: form.subhead,
    sponsor_first: form.sponsor_first,
    sponsor_second: form.sponsor_second,
    selectedValue: form.selectedValue,
    group: form.group,
    group_num: Number(form.group_num),
    time: form.time,
    remainTime: form.remainTime,
    styleRadio: form.styleRadio,
    glitterRadio: form.glitterRadio,
    selectedImage: form.selectedImage,
    xuanshou: tableData.value
  }
  if (tableData.value.length !== 0) {
    store.formData.group_num = tableData.value.length

    // 更改前端组数值并设置为不可更改
    form.group_num = tableData.value.length
    inputNumDisable()
  }
}

function inputNumDisable() {
  const group_num_input = document.getElementById('group-num-input')
  const group_num_box = document.getElementById('group-num-box')
  group_num_box.style.disable = true
  group_num_input.style.cursor = 'not-allowed'
}

// 使用 watch 监听表单数据变化
watch(
  () => ({
    active_name: form.active_name,
    subhead: form.subhead,
    sponsor_first: form.sponsor_first,
    sponsor_second: form.sponsor_second,
    selectedValue: form.selectedValue,
    group: form.group,
    group_num: Number(form.group_num),
    time: form.time,
    remainTime: form.remainTime,
    styleRadio: form.styleRadio,
    glitterRadio: form.glitterRadio,
    selectedImage: form.selectedImage,
    xuanshou: tableData.value
  }),
  () => {
    saveFormData()
  },
  { deep: true }
)

//倒计时样式选择

const styleOptions = [
  { value: 'option1', label: '电子钟' },
  { value: 'option2', label: '时钟' }
]
const groupOptions = [
  { value: 'option1', label: '无' },
  { value: 'option2', label: '本科院校组' },
  { value: 'option3', label: '高职高专院校组' }
]
const remainOptions = [
  { value: 'option1', label: '10' },
  { value: 'option2', label: '30' },
  { value: 'option3', label: '60' }
]

//

//图片选择点击效果
function selectImage(image) {
  form.selectedImage = image
  console.log(form.selectedImage)
}

//背景图片上传
const fileInput = ref(null)
const triggerFileInput = () => {
  fileInput.value.click()
}
const onFileChange = (event) => {
  const file = event.target.files[0]
  if (file && file.type.startsWith('image/')) {
    const reader = new FileReader()
    reader.onload = (e) => {
      images.push(e.target.result)
    }
    reader.readAsDataURL(file)
  }
}
</script>
